﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Logic;
using Atmk.WaterMeter.MIS.LogicTestForm.Common;
using Autofac;
using NKnife.Win.Forms;
using NLog;

namespace Atmk.WaterMeter.MIS.LogicTestForm.Dialogs
{
    public partial class LoginDialog : SimpleForm
    {
        private static readonly ILogger _Logger = LogManager.GetCurrentClassLogger();
        private readonly ILoginLogic _LoginLogic;
        private readonly IUserCenterLogic _userCenterLogic;


        public LoginDialog(
            ILoginLogic LoginLogic,
            IUserCenterLogic userCenterLogic
            )
        {
            _LoginLogic = LoginLogic;
            _userCenterLogic = userCenterLogic;
            InitializeComponent();
            _acceptButton.Click += (s, e) => { GetToken(_userNameTextBox.Text, _passwordTextBox.Text); };
            _LoginInButton.Click += (s, e) =>
            {
                SingleVariable.Instance().Token.payload.areaid = comboBox1.SelectedValue.ToString();
                Close();
            };
        }

        private void GetToken(string name, string password)
        {
                var login = _LoginLogic;
                if (login.LoginMatching(name, password, out string staffid, out string roleid, out string areaid))
                {
                    var token = new Token
                    {
                        payload = { id = staffid, name = name, role = roleid, areaid = areaid }
                    };
                    SingleVariable.Instance().Token = token;
                    ConfigArea(token);
                    _Logger.Trace("获取token数据");
                }
                else
                {
                    MessageBox.Show("登陆失败");
                }
           
          
        }

        private void ConfigArea(Token token)
        {
            if (token.payload.name.ToLower() == "admin")
            {
                var areas = _userCenterLogic.SelectUserSite(token.payload.id).siteList;
                var item = areas.Select(a => new
                {
                    key = a.id,
                    value = a.siteName
                });
                comboBox1.DataSource = item.ToList();
                comboBox1.DisplayMember = "value";
                comboBox1.ValueMember = "key";
            }
            else
            {
                Close();
            }
        }
    }
}